// pages/share/share.js
var utils = require('../../../utils/util.js');
var QRCode = require('../../../utils/weapp-qrcode.js');
var radius = require('../../../utils/canvas-radius.js');
var qrcode;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canvasHidden: true, //设置画板的显示与隐藏，画板不隐藏会影响页面正常显示
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.personalInfo();
    const res = wx.getSystemInfoSync()
    console.log(res)
    that.setData({
      screenWidth: res.screenWidth,
      screenHeight: res.windowHeight
    })

  },
  //我的个人信息
  personalInfo: function(e) {
    var that = this;
    utils.http("/api/v1/member/index", {}, function(res) {
      that.setData({
        userInfo: res.datas
      })
      wx.downloadFile({
        url: res.datas.avatar,
        success: function(result) {
          that.setData({
            avatar: result.tempFilePath
          })
        }
      })
      var text = 'https://xinong.qidian2018.com/index.php?share_id=1&type=4&member_id=' + that.data.userInfo.id;
      console.log('text', text)
      qrcode = new QRCode('canvas', {
        text: text,
        width: 100,
        height: 100,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });

    })
  },

  shiftSize: function(w) {
    var res = wx.getSystemInfoSync()
    var v = 375 / res.windowWidth; //设计稿尺寸除以当前手机屏幕宽度
    return w / v;
  },
  //定义的保存图片方法
  saveImageToPhotosAlbum: function() {
    var that = this;
    that.setData({
      canvasHidden: false
    })
    wx.showLoading({
      title: '保存中...',
    });
    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      success: function(res) {
        that.setData({
          rwm: res.tempFilePath
        }, function() {
          //设置画板显示，才能开始绘图
          var unit = that.data.screenWidth / 375;
          console.log(unit)
          // return;
            var butback = "https://xinong.qidian2018.com/smimgs/shareImg.jpg"; //背景图;
          var avatarImg = that.data.avatar;
          var rwm = that.data.rwm;
          var text = "这里可以写一写文案,比如快来加入囍农大家庭吧！邀请好友一起享受美味水果～这里的水果四季如春"
          var context = wx.createCanvasContext('share');

          console.log(that.data.screenWidth, that.data.screenHeight)
          //背景图
          context.drawImage(butback, 0, 0, that.data.screenWidth, that.data.screenHeight);
          //内容白色背景
          radius.fillRoundRect(context, 26 * unit, 262 * unit, unit * 324, unit * 214, 10 * unit, '#fff');
          //二维码
          console.log('rwmrwmrwmrwmrwmrwm', rwm)
          context.drawImage(rwm, 50 * unit, 310 * unit, unit * 114, unit * 114);
          //正文换行
          var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
          var temp = "";
          var row = [];
          context.setFontSize(12)
          context.setFillStyle("#000")
          for (var a = 0; a < chr.length; a++) {
            if (context.measureText(temp).width < 130 * unit) {
              temp += chr[a];
            } else {
              a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
              row.push(temp);
              temp = "";
            }
          }
          row.push(temp);
          //如果数组长度大于2 则截取前两个
          if (row.length > 2) {
            var rowCut = row.slice(0, 4);
            var rowPart = rowCut[1];
            var test = "";
            var empty = [];
            for (var a = 0; a < rowPart.length; a++) {
              if (context.measureText(test).width < 1200 * unit) {
                test += rowPart[a];
              } else {
                break;
              }
            }
            empty.push(test);
            var group = empty[0] //这里只显示两行，超出的用...表示
            rowCut.splice(1, 1, group);
            row = rowCut;
          }
          console.log(row)
          for (var b = 0; b < row.length; b++) {
            context.fillText(row[b], 178 * unit, (330 + b * 20) * unit, 600 * unit);
          }
          //头像
          radius.strokeRoundRect(context, 194 * unit, 264 * unit, 34 * unit);
          context.save(); //保存画图板
          context.beginPath() //开始创建一个路径
          context.arc(194 * unit, 264 * unit, 34 * unit, 0, 2 * Math.PI, false) //画一个圆形裁剪区域
          context.clip(); //裁剪
          context.closePath();
          context.drawImage(avatarImg, 160 * unit, 230 * unit, unit * 68, unit * 68);
          context.restore();

          //把画板内容绘制成图片，并回调 画板图片路径
          setTimeout(function() {
            context.draw(false, function() {
              wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: unit * 375 * 2,
                height: unit * 567 * 2,
                destWidth: unit * 375 * 2,
                destHeight: unit * 567 * 2,
                canvasId: 'share',
                success: function(res) {
                  that.setData({
                    shareImgPath: res.tempFilePath
                  });
                  if (!res.tempFilePath) {
                    wx.showModal({
                      title: '提示',
                      content: '图片绘制中，请稍后重试',
                      showCancel: false
                    })
                  }
                  //画板路径保存成功后，调用方法吧图片保存到用户相册
                  wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    //保存成功失败之后，都要隐藏画板，否则影响界面显示。
                    success: (res) => {
                      //  console.log(res)
                      wx.hideLoading()
                      wx.showToast({
                        title: '已保存至相册',
                      })
                      that.setData({
                        canvasHidden: true
                      })
                    },
                    fail: (err) => {
                      // console.log(err)
                      wx.hideLoading()
                      wx.showToast({
                        title: '未保存至相册',
                        icon: 'none'
                      })
                      that.setData({
                        canvasHidden: true
                      })
                    }
                  })
                }
              })
            });
          }, 200)
        })
      }
    }, that)

  },
  /**
   * 用户点击右上角分享（index.js）
   */
  onShareAppMessage: function(ops) {
    var that = this;
    console.log(that.data.info)
    if (ops.from === 'button') {
      // 来自页面内转发按钮
      console.log(ops.target)
    }
    return {
      title: '向本',
      path: 'pages/index/index',
      success: function(res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
        console.log(res);
      },
      fail: function(res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }

  },

})